package edu.nju.desserthouse.dao.impl;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import nju.edu.desserthouse.model.Shop;

import edu.nju.desserthouse.dao.ShopDao;

/**
 * Session Bean implementation class ShopDao
 */
@Stateless
public class ShopDaoBean implements ShopDao{
	
	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName = "desserthouseJPA")
	protected EntityManager em;
	
	public ShopDaoBean(){
		
	}

	@Override
	public boolean save(Shop shop) {
		try{
			em.persist(shop);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Shop find(String column, String value) {
		Shop shop = null;
		try{
			Query query = em.createQuery("from Shop s where s." + column + "=" + value);
			shop = (Shop)query.getSingleResult();
			em.clear();
			return shop;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean updateByShopId(Shop shop) {
		try{
			em.merge(shop);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public long getShopNum() {
		try{
			Query query = em.createQuery("SELECT COUNT(s) from Shop s");
			long count = (Long) query.getSingleResult();
			em.clear();
			return count;
		}catch(Exception e){
			e.printStackTrace();
			return 0;
		}
	}
	
}
